'use strict'

const Controller = require('egg').Controller
const jwt = require('jsonwebtoken')

class HomeController extends Controller {
  async index() {
    const { ctx } = this
    ctx.body = 'hi, egg'
  }

  async getTest() {
    const { ctx, app } = this
    const { page, size } = ctx.query
    // crm 方式， 对象语法 ， 查询数据库
    /**
     * select 查询所有数据
     * get 查询一条数据
     */
    //  const data = await this.app.mysql.get('users', { id: 3 })
    // const data = await this.app.mysql.select('users', {
    //   // where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE 条件
    //   columns: ['id', 'username', 'nickname'], // 要查询的表字段
    //   // orders: [['created_at','desc'], ['id','desc']], // 排序方式
    //   orders: [['id', 'desc']],
    //   limit: size * 1,
    //   offset: (page - 1) * size * 1,
    // })

    // const data = await this.app.mysql.query(
    //   `select id, username, nickname from users order by id desc limit ? offset ?`,
    //   [size * 1, (page - 1) * size * 1]
    // )

    // const data = await this.app.mysql.query(
    //   `select * from users where username like '%${'由'}%'`
    // )

    // const data = await this.app.mysql.query(
    //   `select * from users where id between 1 and 2`
    // )

    // const data = await this.app.mysql.query(`select * from users where id > 10`)

    ctx.body = new ctx.SussessModel(data)
  }

  async postTest() {
    const { ctx } = this
    const body = ctx.request.body
    // 添加数据
    // const insertData = await this.app.mysql.insert('users', {
    //   ...body,
    //   password: ctx.getPassword(body.password),
    // })

    // 修改数据
    // const insertData = await this.app.mysql.update('users', body)

    // 删除数据
    // const deleteData = await this.app.mysql.delete('code', body)

    ctx.body = {}
  }

  async getLogin() {
    const { ctx, app } = this
    try {
      const { username, password } = ctx.request.body
      const data = await app.mysql.query(
        `select * from users where username=? and password=?`,
        [username, ctx.getPassword(password)]
      )
      const token = jwt.sign(
        { id: data[0].id, username: data[0].username },
        app.config.secretKey,
        {
          expiresIn: '24h',
        }
      )
      ctx.body = new ctx.SussessModel(token)
    } catch (err) {
      ctx.body = new ctx.FailModel(err)
    }
  }

  async getUserList() {
    const { ctx, app } = this
    const res = await app.mysql.query(`select * from users`)
    ctx.body = new ctx.SussessModel(res)
  }
}

module.exports = HomeController
